﻿/*****************************************介绍*****************************************
 * 作者：User
 * 创建时间：2025-06-16 18:02:30
 * 功能：序列帧播放器
**************************************************************************************/

using System;
using UnityEngine;
using UnityEngine.UI;

public class SpriteSequencePlayer : MonoBehaviour
{
    [Header("序列帧设置")]
    [Tooltip("序列帧图片数组")]
    public Sprite[] sprites;

    [Tooltip("播放速度（每秒播放帧数）")]
    [Range(1, 120)] public float speed = 30;

    [Tooltip("是否循环播放")]
    public bool loop = true;

    [Tooltip("是否在启动时自动播放")]
    public bool playAutomatically = true;

    // 事件定义
    public event Action OnStart;          // 开始播放时触发
    public event Action<int> OnPlay;      // 播放每帧时触发（参数：当前帧索引）
    public event Action OnPause;          // 暂停时触发
    public event Action OnResume;         // 恢复播放时触发
    public event Action OnComplate;       // 播放完成时触发（非循环模式）
    public event Action OnStop;           // 停止时触发

    private Image img;
    private int currentIndex;
    private float timer;
    private bool isPlaying;
    private bool isPaused;
    private bool initialized;

    private void Start()
    {
        Initialize();
    }

    private void OnEnable()
    {
        // 如果对象被重新激活，且配置了自动播放
        if (initialized && playAutomatically && !isPlaying)
        {
            Play();
        }
    }

    private void OnDisable()
    {
        Stop();
    }

    private void Initialize()
    {
        if (initialized) return;

        img = GetComponent<Image>();

        if (img == null)
        {
            Debug.LogError("缺少SpriteRenderer组件！");
            enabled = false;
            return;
        }

        if (sprites == null || sprites.Length == 0)
        {
            Debug.LogError("未设置序列帧图片！");
            enabled = false;
            return;
        }

        // 初始化为第一帧
        ResetPlayback();

        // 根据配置决定是否自动播放
        if (playAutomatically)
        {
            Play();
        }

        initialized = true;
    }

    private void Update()
    {
        if (!isPlaying || isPaused) return;

        float frameDuration = 1f / speed;
        timer += Time.deltaTime;

        if (timer >= frameDuration)
        {
            // 计算需要前进的帧数（处理跳帧情况）
            int framesToAdvance = Mathf.FloorToInt(timer / frameDuration);
            timer %= frameDuration;

            // 更新当前帧索引
            currentIndex += framesToAdvance;

            // 检查是否播放完成
            if (currentIndex >= sprites.Length)
            {
                if (loop)
                {
                    // 循环模式：回到开头
                    currentIndex %= sprites.Length;
                    OnComplate?.Invoke();
                }
                else
                {
                    // 非循环模式：停止播放
                    Stop();
                    OnComplate?.Invoke();
                    return;
                }
            }

            // 更新显示的Sprite
            img.sprite = sprites[currentIndex];

            // 触发帧播放事件
            OnPlay?.Invoke(currentIndex);
        }
    }

    /// <summary>
    /// 开始/继续播放序列帧
    /// </summary>
    public void Play()
    {
        if (sprites == null || sprites.Length == 0) return;

        if (!isPlaying)
        {
            // 首次播放
            isPlaying = true;
            isPaused = false;
            OnStart?.Invoke();
            OnPlay?.Invoke(currentIndex);
        }
        else if (isPaused)
        {
            // 从暂停恢复
            isPaused = false;
            OnResume?.Invoke();
        }
    }

    /// <summary>
    /// 暂停播放（保留当前进度）
    /// </summary>
    public void Pause()
    {
        if (!isPlaying || isPaused) return;

        isPaused = true;
        OnPause?.Invoke();
    }

    /// <summary>
    /// 停止播放（重置进度）
    /// </summary>
    public void Stop()
    {
        if (!isPlaying) return;

        ResetPlayback();
        isPlaying = false;
        isPaused = false;
        OnStop?.Invoke();
    }

    /// <summary>
    /// 重置播放状态到第一帧
    /// </summary>
    public void ResetPlayback()
    {
        currentIndex = 0;
        timer = 0;

        if (sprites != null && sprites.Length > 0)
        {
            img.sprite = sprites[0];
        }
    }

    /// <summary>
    /// 设置播放速度
    /// </summary>
    /// <param name="newSpeed">新的播放速度（FPS）</param>
    public void SetSpeed(float newSpeed)
    {
        speed = Mathf.Clamp(newSpeed, 0.1f, 240);
    }

    /// <summary>
    /// 跳转到指定帧
    /// </summary>
    /// <param name="frameIndex">目标帧索引</param>
    public void GotoFrame(int frameIndex)
    {
        if (sprites == null || sprites.Length == 0) return;

        currentIndex = Mathf.Clamp(frameIndex, 0, sprites.Length - 1);
        img.sprite = sprites[currentIndex];
        timer = 0;
        OnPlay?.Invoke(currentIndex);
    }

    /// <summary>
    /// 设置是否自动播放
    /// </summary>
    public void SetPlayAutomatically(bool autoPlay)
    {
        playAutomatically = autoPlay;

        // 如果启用自动播放且当前未播放，则开始播放
        if (playAutomatically && !isPlaying)
        {
            Play();
        }
    }

    public void RemoveAll_OnStartEvent() => OnStart = null;
    public void RemoveAll_OnPlayEvent() => OnPlay = null;
    public void RemoveAll_OnPauseEvent() => OnPause = null;
    public void RemoveAll_OnResumeEvent() => OnResume = null;
    public void RemoveAll_OnComplateEvent() => OnComplate = null;
    public void RemoveAll_OnStopEvent() => OnStop = null;

    // 属性访问器
    public bool IsPlaying => isPlaying && !isPaused;
    public bool IsPaused => isPaused;
    public int CurrentFrame => currentIndex;
    public int TotalFrames => sprites != null ? sprites.Length : 0;
    public bool PlayAutomatically => playAutomatically;
}